package com.ald.crossex.system.wechat;

import com.ald.crossex.dto.wechat.WechatTicketResponse;
import com.ald.crossex.system.SystemCache;
import com.ald.crossex.system.SystemCacheItem;
import com.ald.crossex.system.SystemConfig;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by lishijiong on 15/2/12.
 * jsapi_ticket是公众号用于调用微信JS接口的临时票据
 */
public class RefreshJsApiTicketJob implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    private RefreshAccessTokenJob refreshAccessTokenJob;
    private static final Logger logger = Logger.getLogger(RefreshJsApiTicketJob.class);

    public void execute() {
        //https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi

        try {

            SystemCacheItem cacheItem = SystemCache.get("access_token");
            if(cacheItem == null){
                refreshAccessTokenJob = (RefreshAccessTokenJob) getBean("refreshAccessTokenJob");
                refreshAccessTokenJob.execute();
                do{
                   Thread.sleep(1000);
                   cacheItem = SystemCache.get("access_token");
                }while (cacheItem != null && !"".equals(cacheItem.getObject()));
            }

            String accessToken = (String) SystemCache.get("access_token").getObject();

            String requestUrl = SystemConfig.getVal("jsapi_ticket_url") + "?access_token=" + accessToken + "&type=jsapi";

            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(requestUrl);
            HttpResponse response = client.execute(get);
            if (response.getStatusLine().getStatusCode() == 200) {
                String jsonResult = getResponseString(response, "UTF-8");

                WechatTicketResponse ticket = JSON.parseObject(jsonResult, WechatTicketResponse.class);
                if (ticket.getErrcode().intValue() == 0) {
                    SystemCache.put("jsapi_ticket", ticket.getTicket());
                    logger.info("刷新微信 jsapi_ticket 成功");
                } else {
                    logger.error("刷新微信 jsapi_ticket 返回错误信息 code:"+ticket.getErrcode()+" message:"+ticket.getErrmsg());
                }

            } else {
                logger.error("刷新微信 jsapi_ticket http请求失败");
            }
        } catch (Exception e) {
           logger.error("刷新微信 jsapi_ticket 失败"+e.getMessage());
        }

    }


    private static String getResponseString(HttpResponse response, String charset)
            throws IOException {
        InputStream inputStream = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                inputStream, charset));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        return buffer.toString();
    }
}
